package com.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.constant.AppConstant;
import lombok.extern.log4j.Log4j2;

import java.io.*;

/**
 * @author Yadasu
 * @date 2021/2/7 10:35
 */
@Log4j2
public class WindowsFtpUtils {


    public static void main(String[] args)  {
        // 服务器ip
        String ipv4Address = "47.111.225.207";
        // freeSshd设置的连接端口
        int port = 22;
        String freeSshdUserName = "administrator";
        String freeSshdUserPassword = "Aimer123!@";
        // 在cmd中执行的命令
//        String command = "cmd /c C:\\Users\\Administrator\\Desktop\\test\\app.bat";
        String command="cmd /c 'echo Hello & echo My Friend'";
        sshServer(ipv4Address, port, freeSshdUserName, freeSshdUserPassword, command);

    }

    public static void sshServer(String ipv4Address, int port, String freeSshdUserName, String freeSshdUserpassword, String command)  {
        Connection conn = new Connection(ipv4Address, port);
        Session session = null;

        try {
            conn.connect();
            // login
            boolean isLogin = conn.authenticateWithPassword(freeSshdUserName, freeSshdUserpassword);
            if (!isLogin)
                throw new IOException("Authentication failed.文件scp到数据服务器时发生异常");

            Session openSession = conn.openSession();
            openSession.execCommand(command);

            System.out.println("The execute command output is:" + openSession.getStdout());
            InputStream is = new StreamGobbler(openSession.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();

            }
            if (conn != null) {
                conn.close();
            }
        }
    }

}
